package cn.com.zaprk.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @PackageName: cn.com.zpark.utils
 * @ClassName: JDBCUtils
 * @Description:JDBC工具类，注册驱动获取连接，关闭连接对象
 * @author: RZS
 * @date: 2021/10/27  10:24
 */
public class JDBCUtils {
    private static String url;
    private static String driver;
    private static String username;
    private static String password;

    // 初始化变量
    static {
        //创建properties集合
        Properties properties = new Properties();
        InputStream inputStream = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbcutils.properties");

        try {
            // 加载配置文件流对象
            properties.load(inputStream);

            // 初始化属性
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接对象
     * @return
     * @throws Exception
     */
    public static Connection getConn() throws Exception {
        // 注册驱动
        Class.forName(driver);
        // 获取连接
        Connection conn = DriverManager.getConnection(url, username, password);
        return conn;
    }

    /**
     * 关闭连接对象
     * @param res
     * @param stat
     * @param conn
     */
    public static void close(ResultSet res, Statement stat, Connection conn){
        if (res != null) {
            try {
                res.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}












